"use client";
import { message } from "antd";
import { getQuestionVoByIdUsingGet } from "@/api/questionController";
import QuestionCard from "@/components/QuestionCard";
import { useEffect, useState } from "react";
import "./index.css";
import { getUserFavoriteQuestionsUsingGet } from "@/api/questionFavoriteController";

interface Props {
  params: {
    questionId: string;
  };
}

/**
 * 题目详情页
 * @constructor
 */
export default function QuestionPage({ params }: Props) {
  const { questionId } = params;
  const [question, setQuestion] = useState<API.QuestionVO>();
  const [isFavorite, setIsFavorite] = useState(false);

  // 获取题目详情
  useEffect(() => {
    const fetchQuestion = async () => {
      try {
        const res = await getQuestionVoByIdUsingGet({
          id: questionId,
        });
        if (res.data) {
          setQuestion(res.data);
        }
      } catch (e) {
        message.error("获取题目详情失败，" + e.message);
      }
    };
    fetchQuestion();
  }, [questionId]);

  // 获取收藏状态
  useEffect(() => {
    const checkFavoriteStatus = async () => {
      try {
        const res = await getUserFavoriteQuestionsUsingGet();
        if (res.data) {
          const favoriteQuestions = res.data as unknown as API.QuestionVO[];
          const isQuestionFavorite = favoriteQuestions.some(q => q.id === parseInt(questionId));
          setIsFavorite(isQuestionFavorite);
        }
      } catch (e) {
        console.error("获取收藏状态失败", e);
      }
    };
    checkFavoriteStatus();
  }, [questionId]);

  // 错误处理
  if (!question) {
    return <div>获取题目详情失败，请刷新重试</div>;
  }

  return (
    <div id="questionPage">
      <QuestionCard 
        question={question} 
        isFavorite={isFavorite}
        onFavoriteChange={setIsFavorite}
      />
    </div>
  );
}
